#include <vector>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
private:
    ListNode* merge(vector<ListNode*>& lists, int left, int right) {
        if (left >= right) {
            return lists[left];
        }
        int middle = (left + right) / 2;
        ListNode* l1 = merge(lists, left, middle);
        ListNode* l2 = merge(lists, middle + 1, right);
        ListNode head(0);
        ListNode* node = &head;
        while (l1 != nullptr && l2 != nullptr) {
            if (l1->val < l2-> val) {
                node->next = l1;
                l1 = l1->next;
            } else {
                node->next = l2;
                l2 = l2->next;
            }
            node = node->next;
        }
        while (l1 != nullptr) {
            node->next = l1;
            l1 = l1->next;
            node = node->next;
        }
        while (l2 != nullptr) {
            node->next = l2;
            l2 = l2->next;
            node = node->next;
        }
        return head.next;
    }
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.empty()) {
            return nullptr;
        }
        return merge(lists, 0, lists.size() - 1);
    }
};

int main() {
    ListNode l1(1), l2(4), l3(5);
    ListNode l4(1), l5(3), l6(4);
    ListNode l7(2), l8(6);
    l1.next = &l2;
    l2.next = &l3;
    l4.next = &l5;
    l5.next = &l6;
    l7.next = &l8;
    Solution solution;
    vector<ListNode*> input = {&l1, &l4, &l7};
    solution.mergeKLists(input);
}